package com.ada;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException, ParseException {

        Analyzer analyzer = new StandardAnalyzer();

        // Store the index in memory:
        // Directory directory = new RAMDirectory();
        // To store an index on disk, use this instead:
        Path path = Paths.get("D:\\lucene");
        Directory directory = FSDirectory.open(path);
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter iwriter = new IndexWriter(directory, config);
        Document doc = new Document();
        String text = "而在网络方面，我只想提java7对异步IO的操作，Asynchronous Channel。这部分是NIO.1非阻塞IO后最大的更新";
        doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
        iwriter.addDocument(doc);
        iwriter.close();

        // Now search the index:
        DirectoryReader ireader = DirectoryReader.open(directory);

        IndexSearcher isearcher = new IndexSearcher(ireader);
        // Parse a simple query that searches for "text":
        QueryParser parser = new QueryParser("fieldname", analyzer);
        Query query = parser.parse("网络");
        ScoreDoc[] hits = isearcher.search(query, 10, Sort.INDEXORDER).scoreDocs;
        // assertEquals(1, hits.length);
        // Iterate through the results:
        System.out.println(hits.length);
        for (int i = 0; i < hits.length; i++) {
            Document hitDoc = isearcher.doc(hits[i].doc);
            // assertEquals("This is the text to be indexed.",
            // hitDoc.get("fieldname"));
            System.out.println(hitDoc.get("fieldname"));

        }
        ireader.close();
        directory.close();

    }
}
